<template>
  <el-card style="height: 80px; margin: 20px 0px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名字">
        <el-input v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-form>
      <el-form-item>
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button
          type="danger"
          :disabled="userDataList.length ? false : true"
          @click="deleteSelectedUsers"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-form-item>
      <el-table border :data="userArr" @selection-change="selectChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column label="用户名字" prop="username"></el-table-column>
        <el-table-column label="用户名称" prop="name"></el-table-column>
        <el-table-column label="用户角色" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" fixed="right" width="400px">
          <template #="{ row }">
            <el-button type="primary" icon="User" @click="setUserRole(row)"
              >分配角色</el-button
            >
            <el-button type="primary" icon="Edit" @click="updateUser(row)"
              >编辑</el-button
            >
            <el-button type="primary" icon="Delete" @click="deleteUser(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        size="large"
        :background="true"
        layout="total,prev, pager, next, jumper, -> , sizes, total"
        :total="total"
        @current-change="getHasUserInfo"
        @size-change="handler"
      />
    </el-form-item>
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userData.id ? '编辑用户信息' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :rules="rules" :model="userData" ref="useFormRef">
          <el-form-item label="用户名字" prop="username">
            <el-input v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input v-model="userData.name"></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            v-if="userData.id ? false : true"
            prop="password"
          >
            <el-input v-model="userData.password"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawer1">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户名">
            <el-input :disabled="true" v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="assignRoles"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="role in allRoles"
                :key="role.id"
                :label="role.roleName"
                :value="role"
              >
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto; margin: 20px 0px">
          <el-button @click="cancel1">取消</el-button>
          <el-button type="primary" @click="confirm1">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<script setup lang="ts">
  import {
    reqDeleteSelectedUsers,
    reqDeleteUser,
    reqSaveOrUpdateUserInfo,
    reqSetUserRole,
    reqUserAndAllRoles,
    reqUserInfoByPage,
  } from '@/api/acl/user'
  import { ref, onMounted, reactive, nextTick } from 'vue'
  import type { RoleData, UserListData } from '@/api/acl/user/type'
  import { ElMessage } from 'element-plus'
  import useLayoutSettingStore from '@/store/modules/layoutSetting'
  let pageNo = ref<number>(1)
  let limit = ref<number>(3)
  let total = ref<number>(100)
  let drawer = ref<boolean>(false)
  let drawer1 = ref<boolean>(false) //控制分配角色抽屉的隐藏与显示
  //收集表单数据
  let userData = reactive<UserListData>({
    username: '',
    password: '',
    name: '',
    id: 0,
  })
  let userArr = ref<UserListData[]>([])
  let useFormRef = ref() //表单实例,用其方法清除校验信息
  let checkAll = ref<boolean>(false)
  let assignRoles = ref<RoleData[]>([]) //存储用户已分配角色数据
  let allRoles = ref<RoleData[]>([]) //存储用户已分配角色数据
  let isIndeterminate = ref<boolean>(false) //控制全选框的中间状态
  let userDataList = ref<UserListData[]>([]) //存储已勾选的数据
  let keyword = ref<string>('') //搜索的关键字
  let settingStore = useLayoutSettingStore()

  const addUser = () => {
    //清除已有数据
    Object.assign(userData, {
      username: '',
      password: '',
      name: '',
      id: 0,
    })
    drawer.value = true
    //清除表单校验信息
    nextTick(() => {
      useFormRef.value.clearValidate('username')
      useFormRef.value.clearValidate('name')
      useFormRef.value.clearValidate('password')
    })
  }

  const updateUser = (row: UserListData) => {
    //给表单项赋值已有数据
    Object.assign(userData, row)
    drawer.value = true
    //清除表单校验信息
    nextTick(() => {
      useFormRef.value.clearValidate('username')
      useFormRef.value.clearValidate('name')
    })
  }

  const getHasUserInfo = async (pager = 1) => {
    pageNo.value = pager
    let result = await reqUserInfoByPage(
      pageNo.value,
      limit.value,
      keyword.value,
    )
    if (result.code === 200) {
      total.value = result.data.total
      userArr.value = result.data.records
    } else {
      ElMessage({ type: 'error', message: '获取用户列表失败' })
    }
  }

  onMounted(() => {
    getHasUserInfo()
  })

  const cancelClick = () => {
    drawer.value = false
  }

  const confirmClick = async () => {
    //发请求前校验表单对象
    await useFormRef.value.validate()
    let result = await reqSaveOrUpdateUserInfo(userData)
    if (result.code === 200) {
      ElMessage({
        type: 'success',
        message: userData.id ? '修改用户成功' : '添加用户成功',
      })
      window.location.reload()
    } else {
      ElMessage({
        type: 'error',
        message: userData.id ? '修改用户失败' : '添加用户失败',
      })
    }
    getHasUserInfo(userData.id ? pageNo.value : 1)
    drawer.value = false
  }

  const handler = () => {
    getHasUserInfo()
  }

  const userNameValidate = (rule: any, value: any, callback: any) => {
    console.log(value)
    if (value.trim().length >= 5 && value.trim().length <= 10) {
      callback()
    } else {
      callback(new Error('用户名的长度必须在5位到10位之间'))
    }
  }

  const nameValidate = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 2) {
      callback()
    } else {
      callback(new Error('名称的长度必须大于1位'))
    }
  }

  const passwordValidate = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 5 && value.trim().length <= 15) {
      callback()
    } else {
      callback(new Error('密码的长度必须在5位到15位之间'))
    }
  }

  const rules = {
    username: { required: true, trigger: 'blur', validator: userNameValidate },
    name: { required: true, trigger: 'blur', validator: nameValidate },
    password: { required: true, trigger: 'blur', validator: passwordValidate },
  }
  //分配角色按钮的回调函数
  const setUserRole = async (row: UserListData) => {
    userData.username = row.username
    userData.id = row.id
    //发请求
    let result = await reqUserAndAllRoles(row.id as number)
    if (result.code === 200) {
      assignRoles.value = result.data.assignRoles
      allRoles.value = result.data.allRolesList
    }
    drawer1.value = true
  }

  //全选框事件回调
  const handleCheckAllChange = (val: any) => {
    assignRoles.value = (val ? allRoles.value : []) as []
    isIndeterminate.value = false
  }

  //复选框组事件回调
  const handleCheckedCitiesChange = (val: any) => {
    const checkedCount = val.length
    checkAll.value = checkedCount === allRoles.value.length
    isIndeterminate.value =
      checkedCount > 0 && checkedCount < allRoles.value.length
  }

  const cancel1 = () => {
    drawer1.value = false
  }

  const confirm1 = async () => {
    let roleIdList = assignRoles.value.map((item) => {
      return item.id
    })
    let result = await reqSetUserRole({
      roleIdList,
      userId: userData.id as number,
    })
    if (result.code === 200) {
      ElMessage({ type: 'success', message: '设置用户角色成功' })
      getHasUserInfo(pageNo.value)
      drawer1.value = false
    } else {
      ElMessage({ type: 'error', message: '设置用户角色失败' })
    }
  }

  //删除按钮事件回调，用于删除单个用户
  const deleteUser = async (row: UserListData) => {
    let result = await reqDeleteUser(row.id as number)
    if (result.code === 200) {
      ElMessage({ type: 'success', message: '删除用户成功' })
      getHasUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
      ElMessage({ type: 'error', message: '删除用户失败' })
    }
  }
  //表格复选框发生变化时的回调
  const selectChange = (val: any) => {
    userDataList.value = val
  }
  //批量删除按钮的事件回调
  const deleteSelectedUsers = async () => {
    let idList = userDataList.value.map((item) => {
      return item.id as number
    })
    let result = await reqDeleteSelectedUsers(idList)
    if (result.code === 200) {
      ElMessage({ type: 'success', message: '批量删除用户成功' })
      getHasUserInfo()
    } else {
      ElMessage({ type: 'error', message: '批量删除用户失败' })
    }
  }

  const search = async () => {
    getHasUserInfo()
    keyword.value = ''
  }

  const reset = () => {
    settingStore.refresh = !settingStore.refresh
  }
</script>

<style scoped>
  .form {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
